import os
from PIL import Image

def convert_multiframe_tif_to_jpg():
    """自动识别当前目录并转换多帧TIF文件"""
    # 获取当前工作目录
    source_dir = os.getcwd()
    # 定义输出目录
    target_dir = os.path.join(source_dir, "target")
    
    # 创建目标目录(自动处理已存在的情况)
    os.makedirs(target_dir, exist_ok=True)
    
    # 遍历当前目录所有文件[1](@ref)
    for filename in os.listdir(source_dir):
        if filename.lower().endswith(('.tif', '.tiff')):
            tif_path = os.path.join(source_dir, filename)
            try:
                with Image.open(tif_path) as img:
                    frame_index = 0
                    while True:
                        try:
                            img.seek(frame_index)
                            # 生成带有序号的文件名[1](@ref)
                            base_name = os.path.splitext(filename)[0]
                            jpg_name = f"{base_name}_frame{frame_index}.jpg"
                            jpg_path = os.path.join(target_dir, jpg_name)
                            # 转换并保存[4](@ref)
                            img.convert('RGB').save(jpg_path, "JPEG", quality=95)
                            print(f"已转换: {filename} 第{frame_index}帧 -> {jpg_name}")
                            frame_index += 1
                        except EOFError:
                            break  # 所有帧处理完成[1](@ref)
            except Exception as e:
                print(f"处理文件 {filename} 时出错: {str(e)}")

if __name__ == "__main__":
    convert_multiframe_tif_to_jpg()
    print("转换完成！所有JPG文件已保存在target文件夹")